/**
 * Created by zhoulin on 2019/4/3.
 */
var companyId = sessionStorageUtils.getJson(storageKey.sessionStorageKey.companyId);
var schoolId = sessionStorageUtils.getJson(storageKey.sessionStorageKey.schoolId);
var schoolMap = sessionStorageUtils.getJson(storageKey.sessionStorageKey.schoolMap);
var E = window.wangEditor;
var editor = new E('#editor');
var app = new Vue({
    el: '#app',
    data: {
        permissions: ['goods:add', 'goods:update'],//本页权限数组
        info: {},
        selects: [],
        specList:[],
        desc: '',
        schoolId: schoolId,
        gBrandList: [],
        goodsList:[],
        typeList:[],
        brandList:[],
    },
    //进入页面初始化方法
    created: function () {
        var that = this;
        var token = sessionStorageUtils.getJson(storageKey.sessionStorageKey.token);
        if (empty(token)) {
            layer.msg("<span style='color:red'>登录超时！请重新登录！</span>", {time: 1500, icon: 5});
            setTimeout(function () {
                window.location.href = _LOGIN_PAGE;
            }, 1200);
            return;
        }
        if (!empty(aGET.id)) {
            that.getInfoById(aGET.id);
            that.initGoodsList();
        } else {
            that.initTypeList();
            that.initBrandList();
            that.initSpec();
        }
    },
    methods: {
        //权限控制
        permission: function (index) {
            return (_PERMISSIONS.indexOf(this.permissions[index]) != -1);
        },
        initTypeList: function (arr) {
            var that = this;
            // var url = _HOST + _API.product_goodsType_list+"?companyId="+companyId;
            var url = _HOST + _API.product_goodsType_list+"?type=2";
            Get(that, url)
                .then(function (res) {
                    if (res.success) {
                        var list = res.list;
                        for (let i = 0; i < list.length; i++) {
                            if (arr != null && arr.length >0) {
                                for (let j = 0; j < arr.length; j++) {
                                    if (list[i].id == arr[j]) {
                                        list[i].isChecked = 1;
                                        break;
                                    }
                                }
                            }
                        }
                        var html = "";
                        for (var item in list) {
                            html = html + '<label class="checkbox-inline i-checks"><input type="checkbox" data-check="'+list[item].isChecked+'" name="goodsType" value="'+list[item].id+'"> '+
                                list[item].name+'</label>'
                        }

                        $("#Form #goodsType").append(html);
                        $("#goodsType .i-checks").iCheck({checkboxClass: "icheckbox_square-green",radioClass: "iradio_square-green",});
                        $("#goodsType input").each(function () {
                            if ($(this).attr("data-check") == 1) {
                                $(this).iCheck('check');
                            }
                        })
                    }
                });
        },
        initBrandList: function (arr) {
            var that = this;
            var url = _HOST + _API.product_goodsBrand_listAll+"?companyId="+companyId+"&schoolId="+schoolId;
            Get(that, url)
                .then(function (res) {
                    if (res.success) {
                        var list = res.rows;
                        for (let i = 0; i < list.length; i++) {
                            if (arr != null && arr.length >0) {
                                for (let j = 0; j < arr.length; j++) {
                                    if (list[i].id == arr[j]) {
                                        list[i].isChecked = 1;
                                        break;
                                    }
                                }
                            }
                        }
                        var html = "";
                        for (var item in list) {
                            html = html + '<label class="checkbox-inline i-checks"><input type="checkbox" data-check="'+list[item].isChecked+'" name="goodsBrand" value="'+list[item].id+'"> '+
                                list[item].name+'</label>'
                        }

                        $("#Form #goodsBrand").append(html);
                        $("#goodsBrand .i-checks").iCheck({checkboxClass: "icheckbox_square-green",radioClass: "iradio_square-green",});
                        $("#goodsBrand input").each(function () {
                            if ($(this).attr("data-check") == 1) {
                                $(this).iCheck('check');
                            }
                        })
                    }
                });
        },
        getInfoById: function (id) {
            var that = this;
            Get(that, _HOST + _API.product_goods_getById + "?id=" + id)
                .then(function (response) {
                    // 响应成功回调
                    if (response.success) {
                        var list = response.data;
                        console.log(list);
                        that.info = list;
                        that.info.oldImgId = list.imgId;
                        for (var item in list) {
                            if (item == 'showUrl') {
                                initFileUpload(list[item]);
                            }
                            if (item == 'imgs') {
                                initFilesUpload(list[item]);
                            }
                            if (item == 'description') {
                                editor.txt.html(list[item]);
                            }
                            if (item == 'specIds') {
                                that.initSpec(list[item]);
                            }
                            if (item == 'typeIds') {
                                if (list[item] != null) {
                                    that.initTypeList(list[item].split(","));
                                } else {
                                    that.initTypeList();
                                }
                            }
                            if (item == 'brandIds') {
                                if (list[item] != null) {
                                    that.initBrandList(list[item].split(","));
                                } else {
                                    that.initBrandList();
                                }
                            }
                        }
                        $("#Form").data('bootstrapValidator').destroy();
                        $('#Form').data('bootstrapValidator', null);
                        Validator();
                    } else {
                        layer.msg(response.msg, {time: 1500, icon: 5});
                    }
                })
        },
        //设置部门
        setDept: function () {
            var that = this;
            var loadingIndex = layer.load(2, { //icon支持传入0-2
                shade: [0.5, 'gray'], //0.5透明度的灰色背景
                content: '数据加载中...',
                success: function (layero) {
                    layero.find('.layui-layer-content').css({
                        'padding-top': '39px',
                        'width': '60px'
                    });
                }
            });
            var setting = {
                check: {
                    enable: true,
                    chkStyle: "radio",
                    radioType: "all"   //对所有节点设置单选
                },
                data: {
                    simpleData: {
                        enable: true,
                        idKey: "id",
                        pIdKey: "parentId",
                        rootPId: 0
                    }
                },
                callback: {
                    onClick: function (e, treeId, treeNode, clickFlag) {
                        console.log(treeNode);
                        // deptId = treeNode.id;
                        // $("#deptName").val(treeNode.name);
                        zTreee.checkNode(treeNode, !treeNode.checked, true);
                    }
                },
            }, zTreee;
            var zNodes = [];
            Get(that, _HOST + _API.product_goodsType_list+"?companyId="+companyId)
                .then(function (response) {
                    // 响应成功回调
                    console.log(response);
                    if (response.success) {
                        if (response.list) {
                            var html = '<ul id="treeDemo" class="ztree"></ul>';
                            var confirm = layer.confirm(html, {
                                title: "套餐类型",
                                btn: ['确定', '取消'], //按钮
                                shadeClose: false,
                                area: ['40%', '98%']
                            }, function () {
                                //选中部门
                                var zTree = $.fn.zTree.getZTreeObj("treeDemo");
                                nodes = zTree.getCheckedNodes(true);
                                if (nodes.length <= 0) {
                                    parent.layer.msg('请选择套餐类型！', {time: 1500, icon: 5});
                                    return;
                                }
                                $("#typeId").val(nodes[0].id);
                                that.info.typeId = nodes[0].id;
                                $("#typeName").val(nodes[0].name);
                                that.info.typeName = nodes[0].name;
                                //单独清除某个字段验证
                                // $('#Form').data('bootstrapValidator').enableFieldValidators('gtName', false);
                                layer.close(confirm);
                            });

                            zTreee = $.fn.zTree.init($("#treeDemo"), setting, response.list);
                            var treeObj = $.fn.zTree.getZTreeObj("treeDemo");

                            var nodes = treeObj.getNodes();
                            if (nodes.length > 0) {
                                for (var i = 0; i < nodes.length; i++) {
                                    treeObj.expandNode(nodes[i], true, false, false);//默认展开第一级节点
                                }
                            }
                            layer.close(loadingIndex);
                        } else {
                            layer.msg(response.msg, {time: 1500, icon: 5});
                        }
                    }
                })
        },
        // 添加
        add: function () {
            var that = this;
            that.info.type = 2;
            that.info.description = editor.txt.html();
            that.info.companyId = companyId;
            that.info.imgIds = $('#uploadImgs').getImgIdArr();
            that.info.goodsIds = that.getGoodsIdList();
            var info = sessionStorageUtils.getParam(storageKey.sessionStorageKey.goods.goodsSpecList);
            that.info.specIds = info.split(',');
            var typeList = [];
            $("#goodsType input[name='goodsType']:checked").each(function () {
                typeList.push($(this).val())
            });
            that.info.typeIds = typeList.join(',');
            var brandList = [];
            $("#goodsBrand input[name='goodsBrand']:checked").each(function () {
                brandList.push($(this).val())
            });
            that.info.brandIds = brandList.join(',');
            // console.log(that.info);
            Post(that, _HOST + _API.product_goods_add, that.info, true, that.permissions[0])
                .then(function (response) {
                    // 响应成功回调
                    console.log(response);
                    if (response) {
                        if (response.success) {
                            layer.msg(response.msg, {time: 1500, icon: 1});
                            setTimeout(function () {
                                window.parent.location.reload(); //刷新父页面
                                layer.closeAll();
                            }, 1500)
                        } else {
                            layer.msg(response.msg, {time: 1500, icon: 5});
                        }
                    }
                    $("#Form").data('bootstrapValidator').destroy();
                    $('#Form').data('bootstrapValidator', null);
                    Validator();
                })
        },
        // 修改
        update: function () {
            var that = this;
            that.info.type = 2;
            that.info.description = editor.txt.html();
            that.info.companyId = companyId;
            that.info.imgIds = $('#uploadImgs').getImgIdArr();
            that.info.goodsIds = that.getGoodsIdList();
            var info = sessionStorageUtils.getParam(storageKey.sessionStorageKey.goods.goodsSpecList);
            that.info.specIds = info.split(',');
            var typeList = [];
            $("#goodsType input[name='goodsType']:checked").each(function () {
                typeList.push($(this).val())
            });
            that.info.typeIds = typeList.join(',');
            var brandList = [];
            $("#goodsBrand input[name='goodsBrand']:checked").each(function () {
                brandList.push($(this).val())
            });
            that.info.brandIds = brandList.join(',');
            // console.log(that.info);
            Post(that, _HOST + _API.product_goods_update, that.info, true, that.permissions[1])
                .then(function (response) {
                    // 响应成功回调
                    console.log(response);
                    if (response) {
                        if (response.success) {
                            layer.msg(response.msg, {time: 1500, icon: 1});
                            setTimeout(function () {
                                window.parent.location.reload(); //刷新父页面
                                layer.closeAll();
                            }, 1500)
                        } else {
                            layer.msg(response.msg, {time: 1500, icon: 5});
                        }
                    }
                    $("#Form").data('bootstrapValidator').destroy();
                    $('#Form').data('bootstrapValidator', null);
                    Validator();
                })
        },
        // 初始化套餐型号
        initSpec: function(arr) {
            var that = this;
            var info = sessionStorageUtils.getParam(storageKey.sessionStorageKey.goods.goodsSpecList);
            var infos = info.split(',');
            var result = [];
            if (!empty(arr) && arr.length>0) {
                result = infos.concat(arr.filter(function(v){return infos.indexOf(v) ===-1}));
                sessionStorageUtils.setParam(storageKey.sessionStorageKey.goods.goodsSpecList,result);
                console.log(result);
            } else {
                result = infos;
            }
            // 得到spec
            if (!empty(result) && result.length>0) {
                Get(that, _HOST + _API.product_goodsSpec_list+"?ids=" + result.join(",")+"&pageNo=1&pageSize=100").then(function (res) {
                    if (res.success) {
                        that.specList = res.rows;
                    }
                });
            }
        },
        // 添加套餐型号
        addOrUpdateSpec: function (id) {
            var that = this;
            var index = layer.open({
                type: 2,
                title: "选择套餐型号",
                content: "../goodsSpec/edit.html?id="+id,
                fix: true,
                shadeClose: true,
                shade: false,
                area: ['60%', '95%'],
                maxmin: true, //开启最大化最小化按钮
                end:function(index){
                    that.initSpec();
                }
            });
            layer.full(index);
        },
        deleteSpec: function (id) {
            var that = this;
            var confirm = layer.confirm('确定删除选中项？', {
                btn: ['确定', '取消'], //按钮
                shadeClose: false,
            }, function () {
                Post(that, _HOST + _API.product_goodsSpec_delete+"?ids=" + id, true)
                    .then(function (response) {
                        // 响应成功回调
                        console.log(response);
                        layer.close(confirm);
                        // 删除当前元素
                        var arr = that.specList;
                        var tmp = [];
                        for (let i = 0; i < arr.length; i++) {
                            if (arr[i].id != id) {
                                tmp.push(arr[i]);
                            }
                        }
                        that.specList = tmp;
                        if (response) {
                            if (response.success) {
                                layer.msg(response.msg, {time: 1500, icon: 1});
                            } else {
                                layer.msg(response.msg, {time: 1500, icon: 5});
                            }
                        }
                    })
            });
        },
        // 选择商品
        initGoodsList: function() {
            var that = this;
            Get(that, _HOST + _API.product_goods_list+"?relationGoodsId=" + aGET.id +"&pageNo=1&pageSize=100").then(function (res) {
                if (res.success) {
                    that.goodsList = res.rows;
                }
            });
        },
        getGoodsIdList: function() {
            var that = this;
            var arr = that.goodsList;
            var tmp = [];
            for (let i = 0; i < arr.length; i++) {
                tmp.push(arr[i].id);
            }
            return tmp;
        },
        addGoods:function () {
            var that = this;
            var index = layer.open({
                type: 2,
                title: "选择关联商品",
                content: "goods.html?id=",
                fix: true,
                shadeClose: true,
                shade: false,
                area: ['60%', '95%'],
                maxmin: true, //开启最大化最小化按钮
                end:function(index){
                    // 获取数据
                    var info = sessionStorageUtils.getJson(storageKey.sessionStorageKey.goods.goodsList);
                    console.log(info);
                    that.goodsList = that.goodsList.concat(info);
                }
            });
            layer.full(index);
        },
        delGoods: function (index) {
            var that = this;
            var arr = that.goodsList;
            var tmp = [];
            for (let i = 0; i < arr.length; i++) {
                if (index != i) {
                    tmp.push(arr[i]);
                }
            }
            that.goodsList = tmp;
        }
    },
});


$('#Form').data('bootstrapValidator', null);
Validator();

function initFileUpload(url) {
    $("#fileUploadBtn").fileinput('destroy');
    $("#fileUploadBtn").fileinput({
        language: "zh",
        uploadUrl: _HOST + _API.common_file_ossUpload,
        ajaxSettings: {
            headers: {
                'Authorization': sessionStorageUtils.getJson(storageKey.sessionStorageKey.token),
                'permCoding': ''
            }
        },
        browseClass: "btn btn-success",
        browseLabel: "上传预览图片",
        browseIcon: "<i class=\"glyphicon glyphicon-picture\"></i> ",
        allowedFileExtensions: ['jpg', 'gif', 'png'],
        showUpload: false,
        dropZoneEnabled: true,
        showPreview: true,
        minFileCount: 1,
        maxFileCount: 1,
        initialPreviewAsData: true,
        initialPreview: [
            url
        ],
        initialPreviewConfig: [
            {
                caption: url,
                size: 329892,
                width: "120px",
                url: url,
                key: 1
            },
        ]
    }).on("filebatchselected", function (event, files) {
        $(this).fileinput("upload");
    }).on("fileuploaded", function (event, data, previewId, index) {
        if (data.response.status) {
            $("#file .file-caption-name").text(data.response.attachemId);
            $("#articleImg").val(data.response.attachemId);
            app.info.imgId = data.response.attachemId;
        } else {
            parent.layer.msg(data.response.msg, {time: 1500, icon: 5});
        }
    });
    $(".kv-file-remove").remove();
}

function initFilesUpload(imgs) {
    var uploadImgs = $('#uploadImgs').diyUpload({
        url: _HOST + _API.common_file_ossUpload,
        begin: function() {
            layer.load(0, {shade: false});
        },
        success: function (data) {
            layer.closeAll();
            console.log("上传成功！");
        },
        error: function (err) {
            layer.closeAll();
            layer.msg(err, {time: 1500, icon: 5});
            console.log("上传失败！");
        },
        headers: {
            'Authorization': sessionStorageUtils.getJson(storageKey.sessionStorageKey.token),
        },
        previewArr: imgs,
        thumb: {
            width: 120,
            height: 90,
            quality: 100,
            allowMagnify: true,
            crop: true,
            type: "image/jpeg"
        }
    });
}

$(function () {
    editor.customConfig.uploadImgServer = _HOST + _API.common_file_ossWe;
    editor.customConfig.uploadFileName = 'file';
    editor.customConfig.uploadImgHeaders = {
        'Authorization': sessionStorageUtils.getJson(storageKey.sessionStorageKey.token),
        'permCoding': '',
        'enctype': 'multipart/form-data'
    };
    editor.customConfig.zIndex = 100;
    editor.create();
    if (empty(aGET.id)) {
        initFileUpload('');
        initFilesUpload('');
    }
});

function Validator() {
    $('#Form').bootstrapValidator({
        fields: {
            name: {
                validators: {
                    notEmpty: {
                        message: '名称不能为空'
                    },
                    stringLength: {
                        max: 100,
                        message: '名称长度最多100个字符'
                    },
                }
            },
        }
    }).on('success.form.bv', function (e) {
        // Prevent form submission
        e.preventDefault();
        if (empty(aGET.id)) {
            app.add();
        } else {
            app.update();
        }
    });
}
